package com.hmall.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author:Cammy.Wu
 * Date:2024-05-26
 * Description:
 */

public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取登录用户信息
        String userInfo = request.getHeader("user-info");

        // 2.判断是否获取了用户，如果有，存入ThreadLocal
        if (StrUtil.isNotBlank(userInfo)) {
            // 将用户信息存入UserContext
            UserContext.setUser(Long.valueOf(userInfo));
        }

        // 3.放行
        return true;
    }

    @Override
    /**
     * Clears the user from the UserContext after the request has been completed.
     *
     * @param request  the HttpServletRequest object
     * @param response the HttpServletResponse object
     * @param handler  the object that handled the request
     * @param ex       any exception that occurred during the request
     * @throws Exception if an error occurs
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户
        UserContext.removeUser();
    }
}
